#!/usr/bin/env python
# -*- coding: UTF-8 -*-

# login_widget.py
#
#  Copyright (c) 2007 INdT (Instituto Nokia de Technologia)
#
#  Author: Kenneth Rohde Christiansen <kenneth.christiansen@gmail.com>
#
#  This program is free software; you can redistribute it and/or
#  modify it under the terms of the GNU General Public License as
#  published by the Free Software Foundation; either version 2 of the
#  License, or (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
#  USA

import pygtk
pygtk.require("2.0")
import gtk
import gobject
import pango
import icon_theme
import gconf
import util

from protocol_combo import ProtocolCombo
from account_dialog import AccountDialog

from gettext import gettext as _

CONFIG_PATH = "/apps/ereseva"

class LoginWidget(gobject.GObject):
    __gproperties__ = {
        'username' : (gobject.TYPE_STRING, 'username for IM account',
                    'username to connect to IM network',
                    '', gobject.PARAM_READWRITE),
        'password' : (gobject.TYPE_STRING, 'password for IM account',
                    'password to connect to IM network',
                    '', gobject.PARAM_READWRITE),
    }
    __gsignals__ = {
        'connection-requested' : (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE,
                    (gobject.TYPE_PYOBJECT, gobject.TYPE_PYOBJECT, ))
    }

    def __init__(self):
        gobject.GObject.__init__(self)

        self.username = ''
        self.password = ''

        self.config_client = gconf.client_get_default ()
        self.config_client.add_dir (CONFIG_PATH, gconf.CLIENT_PRELOAD_NONE)

        self.login_alignment = gtk.Alignment(0.5, 0.5, 1, 1)
        self.login_alignment.set_border_width(18)

        self.vbox3 = gtk.VBox(False, 0)
        self.login_alignment.add(self.vbox3)

        self.icon_theme = icon_theme.icon_theme_get_default()

        self.logo_pixbuf = self.icon_theme.load_icon("ereseva", 128, 0)

        self.logo = gtk.Image()
        self.logo.set_from_pixbuf(self.logo_pixbuf)
        self.vbox4 = gtk.VBox(False, 0)
        self.vbox3.pack_start(self.logo, False, True, 0)

        self.vbox3.pack_start(self.vbox4, False, True, 0)
        self.vbox4.set_border_width(3)

        self.label_user = gtk.Label(_("Username:"))
        self.vbox4.pack_start(self.label_user, False, True, 3)
        self.label_user.set_alignment(0, 0.5)

        self.account_id_entry = gtk.Entry()

        username = self.config_client.get_string(CONFIG_PATH + "/user-name")

        if username:
            self.account_id_entry.set_text(username)

        self.vbox4.pack_start(self.account_id_entry, False, True, 0)
        #self.account_id_entry.set_invisible_char(9679)
        self.account_id_entry.connect('key-press-event', self.on_key_pressed)

        self.vbox5 = gtk.VBox(False, 0)
        self.vbox3.pack_start(self.vbox5, False, True, 0)
        self.vbox5.set_border_width(3)

        self.label_password = gtk.Label(_("Password:"))
        self.vbox5.pack_start(self.label_password, False, True, 3)
        self.label_password.set_alignment(0, 0.5)

        self.password_entry = gtk.Entry()
        self.password_entry.set_visibility(False)
        password = self.config_client.get_string(CONFIG_PATH + "/password")

        if password:
            self.password_entry.set_text(password)

        self.vbox5.pack_start(self.password_entry, False, True, 0)
        self.password_entry.connect('key-press-event', self.on_key_pressed)

        self.checkbutton_passwd = gtk.CheckButton(_("Remember password"))
        self.vbox3.pack_start(self.checkbutton_passwd, False, False, 6)
        self.checkbutton_passwd.set_border_width(3)
        remember_password = self.config_client.get_bool(CONFIG_PATH + \
            "/remember-password")
        self.checkbutton_passwd.set_active(remember_password)

        self.buttonbox = gtk.HButtonBox()
        self.vbox3.pack_start(self.buttonbox, False, False, 0)
        self.buttonbox.set_layout(gtk.BUTTONBOX_END)

        self.button_sign_in = gtk.Button()
        self.button_sign_in.connect("clicked", self.on_signin_clicked)
        self.buttonbox.add(self.button_sign_in)
        self.button_sign_in.set_border_width(3)

        self.alignment_button = gtk.Alignment(0.5, 0.5, 0, 0)
        self.button_sign_in.add(self.alignment_button)

        self.hbox4 = gtk.HBox(False, 2)
        self.alignment_button.add(self.hbox4)

        self.image_connect = gtk.Image()
        self.image_connect.set_from_stock("gtk-connect", gtk.ICON_SIZE_BUTTON)
        self.hbox4.pack_start(self.image_connect, False, False, 0)

        self.label_sign_in = gtk.Label(_("Sign In"))
        self.hbox4.pack_start(self.label_sign_in, False, False, 0)

        self.fony = gtk.VBox(False, 0)
        self.fony.set_size_request(-1, 40)
        self.vbox3.pack_start(self.fony, False, False, 0)

        self.vbox10 = gtk.VBox(False, 0)
        self.vbox3.pack_start(self.vbox10, True, False, 0)
        self.vbox10.set_border_width(3)

        self.account_label = gtk.Label(_("IM Network:"))
        self.vbox10.pack_start(self.account_label, False, True, 3)
        self.account_label.set_alignment(0, 0.5)

        self.protocol_combo = ProtocolCombo()
        self.protocol_combo.set_row_separator_func(self.separator_func)
        self.protocol_combo.connect('changed', self.on_protocol_combo_changed)
        self.vbox10.pack_start(self.protocol_combo, True, False, 0)

        protocol_store = self.protocol_combo.get_model()
        protocol_store.append([None, "--", "", -1, True])
        protocol_store.append([None, _("Advanced..."), "", -1, True])

        self.last_protocol_selected = 0
        self.protocol_combo.set_active(self.last_protocol_selected)


    def separator_func (self, model, row_iter):
        return (model.get_value(row_iter, 1) == "--")


    def get_widget(self):
        """
        Returns the main widget.
        """

        return self.login_alignment


    def do_get_property(self, property):
        """
        Function that is used by the build-in gobject get_property()
        """

        if property.name == 'username':
            return self.username
        elif property.name == 'password':
            return self.password
        else:
            raise AttributeError, 'unknown property %s' % property.name


    def do_set_property(self, property, value):
        """
        Function that is used be the build in gobject set_property()
        """

        if property.name == 'username':
            self.username = value
            self.account_id_entry.set_text(value)
        elif property.name == 'password':
            self.password = value
            self.password_entry.set_text(value)
        else:
            raise AttributeError, 'unknown property %s' % property.name

    def on_key_pressed(self, widget, event):
        # dont do this if shift is pressed together with enter
        if gtk.gdk.keyval_name(event.keyval) in ('Return', 'KP_Enter'):
            self.on_signin_clicked(self.button_sign_in)
            return True

        return False

    def on_signin_clicked(self, button):
        username = self.account_id_entry.get_text()
        password = self.password_entry.get_text()

        if not username or not password: 
            dlg = gtk.MessageDialog(None, 0, gtk.MESSAGE_WARNING,
            gtk.BUTTONS_OK, _("Username and/or password missing!"))
            dlg.run()
            dlg.destroy()
            return

        remember_password = self.checkbutton_passwd.get_active()
        self.config_client.set_string(CONFIG_PATH + "/user-name", username)

        if remember_password:
            self.config_client.set_string(CONFIG_PATH + "/password", password)
        else:
            self.config_client.set_string(CONFIG_PATH + "/password", '')

        self.config_client.set_bool(CONFIG_PATH + "/remember-password", remember_password)
        self.login_alignment.set_sensitive(False)
        self.emit('connection-requested', username, password)

    def on_protocol_combo_changed(self, widget):
        iter = self.protocol_combo.get_active_iter()
        protocol_store = self.protocol_combo.get_model()
        option = protocol_store.get(iter, ProtocolCombo.COMBO_ACCOUNT_TEXT)[0]

        if option == _("Advanced..."):
            self.protocol_combo.set_active(self.last_protocol_selected)
            iter = self.protocol_combo.get_active_iter()
            protocol = protocol_store.get(iter, ProtocolCombo.COMBO_ACCOUNT_PROTOCOL)[0]

            account_dialog = AccountDialog()
            account_dialog.set_account_data(protocol,
                            self.account_id_entry.get_text(),
                            self.password_entry.get_text())

            account_dialog.run()
            account_dialog.destroy()
        else:
            self.last_protocol_selected = self.protocol_combo.get_active()

    def hide(self):
        self.login_alignment.set_sensitive(False)
        self.login_alignment.hide()

    def show(self):
        self.login_alignment.set_sensitive(True)
        self.account_id_entry.grab_focus()
        self.login_alignment.show()


if __name__ == "__main__":
    main_window = gtk.Window(gtk.WINDOW_TOPLEVEL)
    login_widget = LoginWidget().get_widget()
    login_widget.set_property('username', 'joe')
    login_widget.set_property('password', 'blah')

    def connect_account(username, password):
        print 'connect_account'
        print username
        print password

    login_widget.connect('connection-requested', connect_account)
    main_window.add(login_widget)
    main_window.show_all()
    main_window.connect('delete-event', gtk.main_quit)

    gtk.main()
